/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-11-12 09:53:59
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-05-29 15:26:13
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useEffect, useRef, useState } from 'react'
import { Button, Popconfirm, Space } from 'antd';
import { SysRoleDomain } from '@/type.d/system/role';
import ResizeTable from '@/components/ResizeTable';
import { DictDataDomain, UserDomain } from '@/type.d/system';
import { pageInfo } from '@/type.d/ajaxResult';
import PageDiv from '@/components/PageDiv';
import { useStore } from '@/store';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormText,
    QueryFilter,
    ProFormTreeSelect
} from '@ant-design/pro-components';
import {
    listRole,
    delRole,
    RoleIndex,
} from '@/api/system/role';
import './index.less';
import { bulidTreeOptions } from '@/utils/tree';
import { SysPostDomain } from '@/type.d/system/post';
import RoleCard from './roleCard';

const Role: React.FC = () => {

    const { layoutStore, userStore } = useStore();

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<SysRoleDomain>>();
    const [queryValue, setQueryValue] = useState<SysRoleDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<SysRoleDomain[]>([]);

    const [sysNormalDisableOptions, setSysNormalDisableOptions] = useState<any[]>([]);


    const [corpTreeOptions, setCorpTreeOptions] = useState<any[]>([]);


    const [userOptions, setUserOptions] = useState<any[]>([]);//用户枚举，用于分配用户信息名称显示

    const [postOptions, setPostOptions] = useState<any[]>([]);//岗位枚举，用于分配岗位信息名称显示

    const [orgs, setOrgs] = useState<any[]>([]);//组织（包含部门）枚举，用于分配岗位信息名称显示

    const [cardData, setCardData] = useState<SysRoleDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);




    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    const newdata = {
    }

    /**
     * 列表字段配置
     */
    const columns: ProColumns<SysRoleDomain>[] = [
        {
            title: '所属公司',
            dataIndex: 'pkCorp',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: corpTreeOptions
            }
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '角色权限字符串',
            dataIndex: 'roleKey',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '创建者',
            dataIndex: 'createBy',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            align: 'left',
            width: '50',
        },
        {
            title: '更新者',
            dataIndex: 'updateBy',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            valueType: 'dateTime',
            align: 'left',
            width: '50',
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_dom: React.ReactNode, entity: SysRoleDomain) => [
                <a key="view" onClick={() => {
                    onView(entity)
                }}>详情</a>,
                <a key="edit" hidden={!userStore.hasPerms('system:role:edit')} onClick={() => {
                    toCard(entity, true)
                }}>修改</a>,
                <a hidden={!userStore.hasPerms('system:role:remove')}>
                    <Popconfirm title="确定要删除数据吗？" okText="是" cancelText="否" onConfirm={() => {
                        onDelete(entity)
                    }}>
                        <a key="delete">删除</a>
                    </Popconfirm>
                </a>


            ],
        },
    ];



    const toCard = (data: SysRoleDomain, isEdit: boolean) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: SysRoleDomain) => {
        toCard(data, false)
    }

    const onDelete = (dedata: SysRoleDomain) => {
        if (dedata.roleId) {
            layoutStore.OpenSpanning()
            delRole(dedata.roleId).then(() => {
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.roleId !== dedata.roleId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }


    const headButton = () => {
        return <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => toCard(newdata, true)}
                hidden={!userStore.hasPerms('system:role:add')}
            >
                新增
            </Button>
        </Space>
    }

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])

    useEffect(() => {
        //初始化完成，加载枚举类数据
        layoutStore.OpenSpanning();

        RoleIndex({}).then((res) => {
            const data = res.data
            if (data && data.dictdatas) {//数据字典枚举信息
                if (data.dictdatas['sysNormalDisable']) {
                    const d: [] = data.dictdatas['sysNormalDisable'];
                    setSysNormalDisableOptions(d.map((item: DictDataDomain) => {
                        return {
                            label: item.dictLabel,
                            value: item.dictValue
                        }
                    }))

                }
            }

            if (data && data.treecorps) {//公司枚举信息
                setCorpTreeOptions(bulidTreeOptions(data.treecorps, 'pkCorp', 'corpName', 'children'))
            }

            if (data && data.users) {//用户枚举信息
                setUserOptions(data.users.map((item: UserDomain) => {
                    return {
                        label: item.nickName,
                        title: item.nickName,
                        value: item.userId,
                        key: item.userId,
                    }
                }))
            }

            if (data && data.posts) {//岗位枚举信息
                setPostOptions(data.posts.map((item: SysPostDomain) => {
                    return {
                        label: item.postName,
                        title: item.postName,
                        value: item.postId,
                        key: item.postId,
                    }
                }))
            }

            if (data && data.orgs) {
                console.log('orgs', data.orgs);

                setOrgs(data.orgs)
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,pageInfo.pageSize])

    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listRole({ ..._data, ...pageInfo }).then((res) => {
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };



    return (<PageDiv>{

        pageStatus === 'List' ? <PageDiv>
            <QueryFilter<SysRoleDomain>
                defaultCollapsed
                labelWidth={'auto'}
                split
                onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                formRef={queryformRef}>
                <ProFormTreeSelect fieldProps={{ treeData: corpTreeOptions }} key='pkCorp' name="pkCorp" label="所属公司" />
                <ProFormText key='roleName' name="roleName" label="角色名称" />
                <ProFormText key='roleKey' name="roleKey" label="角色权限字符串" />
            </QueryFilter>
            <ResizeTable<SysRoleDomain>
                onRow={record => {
                    return {
                        onDoubleClick: event => {
                            onView(record)
                        },
                    };
                }}
                dataSource={tableListDataSource}
                actionRef={actionRef}
                columns={columns}
                cardBordered
                revalidateOnFocus={false}
                pagination={{
                    ...pageInfo,
                    showTitle: false,
                    onChange: onPageChange
                }}
                headerTitle={headButton()}
            >
            </ResizeTable>
        </PageDiv> :
            <RoleCard
                onBack={() => setPageStatus('List')}
                isedit={isedit}
                setIsedit={setIsedit}
                newdata={newdata}
                userOptions={userOptions}
                postOptions={postOptions}
                orgs={orgs}
                sysNormalDisableOptions={sysNormalDisableOptions}
                cardData={cardData}
                tableListDataSource={tableListDataSource}
                setTableListDataSource={setTableListDataSource} />}
    </PageDiv>

    )
}
export default Role;